<?php
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/26 0026
 * Time: 14:35
 */

namespace HiCommon\Service;

use HiCommon\Repository\AdminsRepository;
use HiCommon\Repository\LogRepository;
use HiCommon\Repository\ShopUserRepository;
use Illuminate\Support\Facades\Hash;

class LoginShopUserService extends BaseService
{


    /**
     * 用户登录-商户后台
     *
     * @param array  $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function web_login_in(array $arr_input)
    {
        $s_username = str_trim($arr_input['username']);
        $s_password = str_trim($arr_input['password']);
        $s_ip =           $arr_input['ip'];

        if(strlen($s_username) <= 0){
            return hello_error('请输入手机号或账号');
        }
        if(strlen($s_password) <= 0){
            return hello_error('请输入密码');
        }

        //验证账户
        $arr_where = [
          'username'=>$s_username,
          'phone'=>$s_username,
        ];
        $arr_option = [
          'with'=>['shop_base']
        ];
        $res = ShopUserRepository::base_get_one_orwhere($arr_where,$arr_option);
        if(is_null($res)){
            return hello_error('用户不存在');
        }
        $arr_shop_user = $res->toarray();
        if($arr_shop_user['pass'] != $s_password){
            return hello_error('密码错误');
        }
        if($arr_shop_user['state'] == 2){
            return hello_error('用户已被禁用');
        }

        $arr_shop = $arr_shop_user['shop_base'];
        if($arr_shop['status'] == 0){
            return hello_error('店铺审核中');
        }
        elseif ($arr_shop['status'] == 2){
            return hello_error('店铺已禁用');
        }
        elseif ($arr_shop['status'] == 3){
            return hello_error('审核失败');
        }
        if($arr_shop['state'] == 2){
            return hello_error('店铺已被禁用');
        }

        $arr_input = [
          'username' => trim((string)$arr_shop_user['username']),
          'password' => trim((string)$s_password),
        ];

        //登录操作-商户后台
        return self::web_attempt($arr_input,$s_ip);

    }

    /**
     * 登录操作-商户后台
     *
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function web_attempt($arr_input,$s_ip = ''){

        //用户登录
        $token = shop_guard()->attempt($arr_input);
        if ($token) {
            //记录登录日志
            $arr_data = [
              'username'=>$arr_input['username'],
              'type'=>'web',
              'ip'=> $s_ip,
              'login_at'=>date('Y-m-d H:i:s')
            ];
            MongoLogService::shop_user_login($arr_data);

            //            //查询登录用户信息
            //            $arr_user = ShopUserRepository::find_one_login(shop_user_id());
            //            $arr_token = [
            //              'user'=>$arr_user,
            //              'access_token' => $token,
            //              'token_type' => 'bearer',
            //              'expires_in' => shop_guard()->factory()->getTTL() * $s_expires_in_time
            //            ];

            return  hello_success('登录成功');
        }
        else {
            return hello_error('登录失败');
        }
    }

    /**
     * 退出登录操作-商户后台
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function web_login_out()
    {
        try {
            //清理缓存
            $arrData =  ['clear'=>[
              'view',
              'route',
              'cache',
              'config',
              'menu',
            ]];
            Clear::clear_cache_operate($arrData);

            //注销用户
            shop_offset_user();
            return hello_success('退出登录');
        } catch (\Exception $exception) {
            return hello_error('失败',[],$exception->getMessage());
        }
    }

    /**
     * 登录操作-商户端app
     *
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function app_attempt($arr_input,$s_ip = ''){
        $s_expires_day = env('web_login_expires_day',10);//有效天数
        $s_expires_hour = $s_expires_day * 24;//有效小时数
        $s_expires_in_time = 60 * $s_expires_hour;//有效分钟数
        
        //用户登录
        $token = web_guard()->attempt($arr_input);
        if ($token) {

            //记录登录日志
            $arr_data = [
              'username'=>$arr_input['username'],
              'type'=>'app',
              'ip'=> $s_ip,
              'login_at'=>date('Y-m-d H:i:s')
            ];
            MongoLogService::shop_user_login($arr_data);

            //查询登录用户信息
            $n_uid = web_user_id();
            $arr_user = ShopUserRepository::find_one_login($n_uid);

            $arr_user = [
              'id'=>$arr_user['id'],
              'type'=>$arr_user['shop_base']['cate'],
              'rong_cloud_id'=>$arr_user['rong_cloud_id'],
              'username'=>$arr_user['username'],
              'nickname'=>$arr_user['nickname'],
              'realname'=>$arr_user['realname'],
              'head_img'=>$arr_user['shop_base']['logo'],
              'phone'=>$arr_user['phone'],
              'sex'=>$arr_user['sex'],
            ];

            $arr_token = [
              'user'=>$arr_user,
              'access_token' => $token,
              'token_type' => 'bearer',
              'expires_in' => web_guard()->factory()->getTTL() * $s_expires_in_time
            ];

            return  hello_success('登录成功',$arr_token);
        }
        else {
            return hello_error('登录失败');
        }
    }

    public function app_web_login_check($arr_shop_user){
        if($arr_shop_user['state'] == 2){
            return hello_error('用户已被禁用');
        }
        $arr_shop = $arr_shop_user['shop_base'];
        if($arr_shop['status'] == 0){
            return hello_error('店铺审核中');
        }
        elseif ($arr_shop['status'] == 2){
            return hello_error('店铺已禁用');
        }
        elseif ($arr_shop['status'] == 3){
            return hello_error('审核失败');
        }
        if($arr_shop['state'] == 2){
            return hello_error('店铺已被禁用');
        }
        if(!in_array($arr_shop['cate'],[1,2])){
            return hello_error('登录失败',[],'商户端暂不支持道路救援商户登录');
        }

        return  hello_success('成功');
    }


    /**
     * 用户登录-商户端app
     *
     * @param array  $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function app_login_in(array $arr_input)
    {
        $s_username = str_trim($arr_input['username']);
        $s_password = str_trim($arr_input['password']);
        $s_ip =           $arr_input['ip'];

        if(strlen($s_username) <= 0){
            return hello_error('请输入手机号或账号');
        }
        if(strlen($s_password) <= 0){
            return hello_error('请输入密码');
        }

        //验证账户
        $arr_where = [
          'username'=>$s_username,
          'phone'=>$s_username,
        ];
        $arr_option = [
          'with'=>['shop_base']
        ];
        $res = ShopUserRepository::base_get_one_orwhere($arr_where,$arr_option);
        if(is_null($res)){
            return hello_error('用户不存在');
        }
        $arr_shop_user = $res->toarray();

        if($arr_shop_user['pass'] != $s_password){
            return hello_error('密码错误');
        }

        //检测商户状态是否符合登录
        $result = LoginShopUserService::app_web_login_check($arr_shop_user);
        if($result['state'] != 0){
            return $result;
        }

        $arr_input = [
          'username' => trim((string)$arr_shop_user['username']),
          'password' => trim((string)$s_password),
        ];

        //登录操作-商户端app
        return self::app_attempt($arr_input,$s_ip);

    }

    /**
     * 手机验证码登录
     *
     * @param $s_phone
     * @param $s_code
     * @param $s_ip
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function app_phonecode_login($s_phone,$s_code,$s_ip){
        $s_phone = str_trim($s_phone);
        $s_code = str_trim($s_code);
        if(mb_strlen($s_phone) <= 0){
            return hello_error('手机号不能为空');
        }
        if(mb_strlen($s_phone) != 11){
            return hello_error('手机号长度错误');
        }
        if(mb_strlen($s_code) <= 0){
            return hello_error('验证码不能为空');
        }


        // TODO IOS包需要固定账户登录
        if($s_phone != '17721086033'){
            $s_real_code = redis_phone_code( $s_phone );
            if (empty($s_real_code)){
                return hello_error('验证码已过期');
            }
            if ($s_real_code != $s_code){
                return hello_error('验证码错误');
            }
        }


        //验证账户
        $arr_where = [
          'phone'=>$s_phone,
        ];
        $arr_option = [
          'with'=>['shop_base']
        ];
        $res = ShopUserRepository::base_get_one($arr_where,$arr_option);
        if(is_null($res)){
            return hello_error('用户不存在');
        }
        $arr_shop_user = $res->toarray();

        //检测商户状态是否符合登录
        $result = LoginShopUserService::app_web_login_check($arr_shop_user);
        if($result['state'] != 0){
            return $result;
        }

        $arr_input = [
          'username' => $arr_shop_user['username'],
          'password' => $arr_shop_user['pass'],
        ];

        //登录操作-商户端app
        $res = self::app_attempt($arr_input,$s_ip);
        if($res['state'] == 0){
            //销毁已使用的手机验证码
            unset_redis_phone_code($s_phone);
        }
        return $res;
    }

    /**
     * 修改密码
     *
     * @param $s_phone
     * @param $s_code
     * @param $s_password
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function app_getback_password($s_phone,$s_code,$s_password){
        $s_phone = str_trim($s_phone);
        $s_code = str_trim($s_code);
        $s_password = str_trim($s_password);
        if(mb_strlen($s_phone) <= 0){
            return hello_error('手机号不能为空');
        }
        if(mb_strlen($s_phone) != 11){
            return hello_error('手机号长度错误');
        }
        if(mb_strlen($s_code) <= 0){
            return hello_error('验证码不能为空');
        }
        if(mb_strlen($s_password) <= 0){
            return hello_error('请输入新密码');
        }
        if(mb_strlen($s_password) <= 5){
            return hello_error('新密码至少6位');
        }
        if(mb_strlen($s_password) > 30){
            return hello_error('请输入30位以内的密码');
        }
        $res = preg_password($s_password);
        if($res['state'] != 0){
            return $res;
        }
        $s_real_code = redis_phone_code( $s_phone );
        if (empty($s_real_code)){
            return hello_error('验证码已过期');
        }
        if ($s_real_code != $s_code){
            return hello_error('验证码错误');
        }

        //验证账户
        $arr_where = [
          'phone'=>$s_phone,
        ];
        $arr_option = [
          'with'=>['shop_base']
        ];
        $res = ShopUserRepository::base_get_one($arr_where,$arr_option);
        if(is_null($res)){
            return hello_error('用户不存在');
        }
        $arr_shop_user = $res->toarray();
        if($arr_shop_user['state'] == 2){
            return hello_error('用户已被禁用');
        }

        $arr_data = [
          'id'=>$arr_shop_user['id'],
          'password'=>Hash::make($s_password),
          'pass'=>$s_password,
        ];

        //修改密码操作
        $res = ShopUserRepository::base_edit_one($arr_data);
        if(!$res){
            return hello_error('密码设置失败');
        }

        //销毁已使用的手机验证码
        unset_redis_phone_code($s_phone);
        return  hello_success('密码设置成功');
    }

}